package com.bodystm.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.time.DateUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bodystm.bean.Oximetry;
import com.bodystm.bean.Patient;
import com.bodystm.dao.OximetryDao;
import com.mimosa.common.dao.HibernateDao;
import com.mimosa.common.service.CommonService;

@Service
@Transactional
public class OximetryService extends CommonService<Oximetry, String> {
	@Resource
	private JdbcTemplate jdbcTemplate;

	@Resource
	private OximetryDao oximetryDao;

	public Oximetry findLatestByEquipNoAndMeasureTime(String equipNo) {
		Query query = this.oximetryDao.createQuery("From Oximetry Where equipNo=? order by measureTime desc", equipNo);
		return (Oximetry) query.setMaxResults(1).uniqueResult();
	}
	
	public List<Oximetry> find24ByEquipNoAndMeasureTime(String equipNo) {
		
		try {
			return oximetryDao.find24ByEquipNoAndMeasureTime(equipNo);//,measureTime);
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			return null;
		}
	}

	/**
	 * 根据mac地址获取所有的温度数据（升序）
	 * 
	 * @param equipNo
	 * @return
	 */
	public List<Oximetry> getAllByEquipNo(String equipNo) {
		try {
			// return temperatureDao.getAllByEquipNo(equipNo);
			Query query = this.oximetryDao.createQuery("From Oximetry Where equipNo=? order by measureTime asc",
					equipNo);
			List<Oximetry> oximetrys = (List<Oximetry>) query.list();
			return oximetrys;
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			return null;
		}
	}
	
	public List<Oximetry> getListIn2Days(){
		Calendar calendar = Calendar.getInstance();
		Date date=new Date();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, -3);
		date = calendar.getTime();
		Query query = this.oximetryDao.createQuery("From Oximetry Where measureTime> ? order by measureTime desc", date);
 		List<Oximetry> oximetrys= (List<Oximetry>)query.list();
 		return oximetrys;
	}

	/**
	 * 鏌ヨ浣撴俯淇℃伅
	 * 
	 * @param equipNo
	 *            璁惧鍙�
	 * @param startTime
	 *            寮�鏃舵椂
	 * @param endTime
	 *            缁撴潫鏃堕棿
	 */
	@SuppressWarnings("unchecked")
	public List<Oximetry> query(final String equipNo, final Date startTime, final Date endTime, Integer rows) {
		if (rows == null) {
			rows = 20;
		}
		String sql = "FROM Oximetry where equipNo=?";
		List<Object> argsList = new ArrayList<Object>();
		argsList.add(equipNo);
		if (startTime != null) {
			argsList.add(startTime);
			sql += " and measureTime>=?";
		}
		if (endTime != null) {
			Date endTimeInfo = new Date(endTime.getTime() + DateUtils.MILLIS_PER_DAY);
			argsList.add(endTimeInfo);
			sql += " and measureTime<?";
		}
		Query query = this.oximetryDao.createQuery(sql);
		int index = 0;
		for (Object obj : argsList) {
			query.setParameter(index++, obj);
		}
		query.setMaxResults(rows);
		return query.list();
	}

	/**
	 * 淇濆瓨娓╁害鏁版嵁淇℃伅
	 * 
	 * @param temperature
	 */
	public void save(Oximetry oximetry) {
		super.saveEntity(oximetry);
	}
	
	public Oximetry getLatestTemprature(final String equipNo){
		Query query = this.getHibernateDao().createQuery("FROM Oximetry where equipNo=? order by measureTime desc", equipNo);
		Oximetry oximetry = (Oximetry) query.setMaxResults(1).uniqueResult();
		return oximetry;
	}

	public Date getLatestDate(final Patient patient, final int distance) {
		// 鏌ヨ鏈�ぇ鐨勬椂闂�
		StringBuilder maxDateSql = new StringBuilder("SELECT max(measureTime) FROM Oximetry where equipNo=?");
		List<Object> paramList = new ArrayList<Object>();
		paramList.add(patient.getEquipNo());
		if (patient.getEndTime() != null) {
			maxDateSql.append(" and measureTime<=?");
			paramList.add(patient.getEndTime());
		}
		Query query = this.oximetryDao.createQuery(maxDateSql.toString());
		int index = 0;
		for (Object obj : paramList) {
			query.setParameter(index++, obj);
		}
		Date date = (Date) query.uniqueResult();
		return date;
	}

	//static final String EXPORT_SQL = "SELECT measureNumOne,measureTime FROM T_Temperature where equipNo=? and measureTime>=DATE_SUB(?, INTERVAL ? DAY)";
	/*static final String EXPORT_SQL = "SELECT measureNumOne,measureTime FROM T_Oximetry where equipNo=? and measureTime>=DATE_SUB(?, INTERVAL ? DAY) GROUP BY DATE_FORMAT(measureTime,'%y-%m-%d %H')";//by rxz 20160219

	public List<Object> getLatestRecord(final Patient patient, final Date maxMeasureDate, final int distance) {
		List<Object> list = null;
		StringBuilder queryBuilder = new StringBuilder(EXPORT_SQL);
		List<Object> paramList = new ArrayList<Object>();
		paramList.add(patient.getEquipNo());
		paramList.add(maxMeasureDate);
		paramList.add(distance);
		if (patient.getEndTime() != null) {
			queryBuilder.append(" and measureTime<=?");
			paramList.add(patient.getEndTime());
		}
		SQLQuery resultQuery = this.temperatureDao.getSession().createSQLQuery(queryBuilder.toString());
		int index = 0;
		for (Object obj : paramList) {
			resultQuery.setParameter(index++, obj);
		}
		list = resultQuery.list();
		return list;
	}*/

	public Oximetry getLatestPoint(final Date lastDate, final String equipNo) {
		Query query = this.getHibernateDao().createQuery("FROM Oximetry where equipNo=? and measureTime>=? order by measureTime desc", equipNo, lastDate);
		Oximetry oximetry = (Oximetry) query.setMaxResults(1).uniqueResult();
		return oximetry;
	}

	@Override
	protected HibernateDao<Oximetry, String> getHibernateDao() {
		return this.oximetryDao;
	}
	/**
	 * 根据集中器设备号获取前一天的温度数据
	 * @param strConcentratorNo
	 * @return
	 */
	public List<Oximetry> getListInOneDayByConcentratorNo(String strConcentratorNo){
		Calendar calendar = Calendar.getInstance();
		Date date=new Date();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, -1);
		date = calendar.getTime();
		Query query = this.oximetryDao.createQuery("From Oximetry Where concentratorNo=? and measureTime> ? order by measureTime desc",strConcentratorNo, date);
 		List<Oximetry> oximetrys= (List<Oximetry>)query.list();
 		return oximetrys;
	}
	
}